package com.jiayi.weiphoto.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.util.HashMap;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.jiayi.weiphoto.activity.MainConstants;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class FileUtil {

	public static boolean deleteImageCacheFile() {
		File imgCacheFile = new File(MainConstants.IMAGE_CACHE);
		if (imgCacheFile.listFiles() == null) {
			return true;
		} else {
			for (File picFile : imgCacheFile.listFiles()) {
				picFile.delete();
			}
			return imgCacheFile.listFiles().length == 0;
		}
	}

	public static class FileExistException extends Exception {
		private static final long serialVersionUID = 1L;
		private static final String ExceptionTag = "FileException";
	}

	public static class DirCreateFailException extends Exception {
		private static final long serialVersionUID = 2L;
		private static final String ExceptionTag = "DirException";
	}

	public static File getFile(String path) throws IOException {
		File file = new File(path);
		if (file.exists()) {
			return file;
		} else {
			File dirFile = new File(path.substring(0,
					path.lastIndexOf(File.separator) + 1));
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}
			if (file.createNewFile()) {
				return file;
			} else {
				return null;
			}
		}
	}

	public static File makeFile(String path) throws IOException {
		return makeFile(
				path.substring(0, path.lastIndexOf(File.separator) + 1),
				path.substring(path.lastIndexOf(File.separator) + 1,
						path.length()));
	}

	public static File makeFile(String dir, String filename) throws IOException {
		File dirF = new File(dir);
		dirF.mkdirs();
		if (dirF.isDirectory()) {
			File file = new File(dir + filename);
			if (file.exists())
				file.delete();
			file.createNewFile();
			if (file.exists()) {
				return file;
			}
		}
		return null;
	}

	public static void makeDirs(String path) throws IOException {
		String sp = java.io.File.separator;
		String[] dirs = path.split(sp);
		String root = "";
		for (String p : dirs) {
			String dir;
			if (root.endsWith(sp)) {
				dir = root + p;
			} else {
				dir = root += sp + p;
			}
			root = dir;
			if (createADir(dir) == false) {
				throw new IOException(String.format("create %s failed", dir));
			}
		}
	}

	public static boolean createADir(String path) {
		File dir = new File(path);
		if (!dir.exists() || dir.isFile()) {
			return dir.mkdirs();
		} else {
			return true;
		}
	}

	public static String getFileName(String path) {
		String name = getFileNameWithExt(path);
		int index = name.lastIndexOf(".");
		if (index > -1) {
			name = name.substring(0, index);
		}
		return name;
	}

	public static String getFileNameWithExt(String path) {
		if (path == null)
			return null;
		int index = path.lastIndexOf("/");
		String name = null;
		if (index > -1) {
			name = path.substring(index + 1, path.length());
		} else {
			name = path;
		}
		return name;
	}

	public static String getFilePath(String file) {
		if (file == null)
			return null;
		int index = file.lastIndexOf("/");
		if (index > -1) {
			return file.substring(0, index);
		}
		return null;
	}

	public static String getFileExt(String path) {
		if (path == null)
			return null;
		int index = path.lastIndexOf(".");
		if (index >= 0) {
			return path.substring(index + 1, path.length()).toLowerCase();
		}
		return null;
	}

	public static boolean isExist(String path) {
		return new File(path).exists();
	}

	public static void rename(String filePath, String newName)
			throws FileExistException {
		if (filePath == null || newName == null)
			return;
		File fe = new File(filePath);
		String newPath = (fe.getParent()).concat(java.io.File.separator)
				.concat(newName).concat(".").concat(getFileExt(filePath));
		if (newName.equals(getFileName(filePath))) {
			return;
		}
		File ft = new File(newPath);
		if (ft.exists())
			throw new FileExistException();
		fe.renameTo(ft);
	}

	public static boolean delete(String path) {
		if (path == null)
			return false;
		File file = new File(path);
		if (file.exists() == false)
			return false;
		String[] subFiles = file.list();
		if (subFiles != null) {
			for (String subName : subFiles) {
				File f = new File(path, subName);
				if (f.isDirectory()) {
					delete(f.getPath());
				} else {
					f.delete();
				}
			}
		}
		return file.delete();
	}
	
	public static File saveBitmapToFile(Bitmap bitmap, String path){
		File resFile = null;
		try {
			resFile = makeFile(path);
			if(resFile == null){
				throw new IOException();
			}
			FileOutputStream fos = new FileOutputStream(resFile);
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
			fos.flush();
			fos.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return resFile;
	}

	public static Resources getResources(Context context, String apkPath)
			throws Exception {
		String PATH_AssetManager = "android.content.res.AssetManager";
		Class assetMagCls = Class.forName(PATH_AssetManager);
		Constructor assetMagCt = assetMagCls.getConstructor((Class[]) null);
		Object assetMag = assetMagCt.newInstance((Object[]) null);
		Class[] typeArgs = new Class[1];
		typeArgs[0] = String.class;
		Method assetMag_addAssetPathMtd = assetMagCls.getDeclaredMethod(
				"addAssetPath", typeArgs);
		Object[] valueArgs = new Object[1];
		valueArgs[0] = apkPath;
		assetMag_addAssetPathMtd.invoke(assetMag, valueArgs);
		Resources res = context.getResources();
		typeArgs = new Class[3];
		typeArgs[0] = assetMag.getClass();
		typeArgs[1] = res.getDisplayMetrics().getClass();
		typeArgs[2] = res.getConfiguration().getClass();
		Constructor resCt = Resources.class.getConstructor(typeArgs);
		valueArgs = new Object[3];
		valueArgs[0] = assetMag;
		valueArgs[1] = res.getDisplayMetrics();
		valueArgs[2] = res.getConfiguration();
		res = (Resources) resCt.newInstance(valueArgs);
		return res;
	}

	public static long getDirSize(File dir) {
		if (dir == null) {
			return 0;
		}
		if (!dir.isDirectory()) {
			return 0;
		}
		long dirSize = 0;
		File[] files = dir.listFiles();
		for (File file : files) {
			if (file.isFile()) {
				dirSize += file.length();
			} else if (file.isDirectory()) {
				dirSize += file.length();
				dirSize += getDirSize(file);
			}
		}
		return dirSize;
	}

	public static String getSize(long size) {
		double s = 0;
		s = (size + 0.0) / (1024 * 1024);
		DecimalFormat df = new DecimalFormat("0.00");
		String filesize = df.format(s);
		return filesize;
	}

	public static Bitmap encodeAsQrBitmap(String contents, BarcodeFormat format,
            int desiredWidth, int desiredHeight) throws WriterException {
        final int WHITE = 0xFFFFFFFF;
        final int BLACK = 0xFF000000;
         
        HashMap<EncodeHintType, String> hints = null;
        String encoding = guessAppropriateEncoding(contents);
        if (encoding != null) {
            hints = new HashMap<EncodeHintType, String>(2);
            hints.put(EncodeHintType.CHARACTER_SET, encoding);
        }
        MultiFormatWriter writer = new MultiFormatWriter();
        BitMatrix result = writer.encode(contents, format, desiredWidth,
                desiredHeight, hints);
        int width = result.getWidth();
        int height = result.getHeight();
        int[] pixels = new int[width * height];
        // All are 0, or black, by default
        for (int y = 0; y < height; y++) {
            int offset = y * width;
            for (int x = 0; x < width; x++) {
                pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
            }
        }
  
        Bitmap bitmap = Bitmap.createBitmap(width, height,
                Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
    }
	
	static String guessAppropriateEncoding(CharSequence contents) {
        // Very crude at the moment
        for (int i = 0; i < contents.length(); i++) {
            if (contents.charAt(i) > 0xFF) {
                return "UTF-8";
            }
        }
        return null;
    }

	public static File getResizedBitmapFile(File bFile) {
		// TODO Auto-generated method stub
		String bigPath = bFile.getAbsolutePath();
		String smallPath = bigPath.substring(0, bigPath.lastIndexOf("."))+"_small"+bigPath.substring(bigPath.lastIndexOf(".")+1, bigPath.length());
		File sFile = new File(smallPath);
		if(sFile.exists()) return sFile;
		return null;
	}
}
